import 'dart:convert';

import 'package:flutter/services.dart';

import '../model/entity.dart';

class CardRequestUtil {
  static Future<List<CardEntity>?> loadCardList() {
    return _loadAsset().then((json) {
      JsonDecoder jsonDecoder = const JsonDecoder();
      Map root = jsonDecoder.convert(json);
      Map data = root["data"];
      List? cards = data["cards"];
      if (cards == null) {
        return Future(() => null);
      }
      List<CardEntity> cardEntities = [];
      for (Map item in cards) {
        Map? originalPost = item["originalPost"];
        if (originalPost != null) {
          String? content = originalPost["content"];
          String? picUrl;
          // List pictures = originalPost["pictures"];
          // if (pictures != null && pictures.length > 0)
          {
            // Map pic = pictures[0];
            Map? pic = originalPost["topic"]["squarePicture"];
            if (pic != null) {
              picUrl = pic["middlePicUrl"];
            }
          }
          if (content != null && picUrl != null) {
            cardEntities.add(CardEntity(picUrl, content));
          }
        }
      }

      return cardEntities;
    });
  }

  static Future<List<ToolBarEntity>?> loadToolList() {
    return _loadAsset().then((json) {
      JsonDecoder jsonDecoder = const JsonDecoder();
      Map root = jsonDecoder.convert(json);
      Map data = root["data"];

      List? toolbarList = data["toolbarItems"];
      if (toolbarList == null) {
        return Future(() => null);
      }
      List<ToolBarEntity> toolbarEntities = [];
      for (Map item in toolbarList) {
        String url = item["url"];
        String? picUrl = item["picUrl"];
        String? title = item["title"];
        if (title != null && picUrl != null) {
          toolbarEntities.add(ToolBarEntity(picUrl, title, url));
        }
      }

      return toolbarEntities;
    });
  }

  static Future<String> _loadAsset() async {
    return await rootBundle.loadString('assets/mock/jk_daily_cards.json');
  }
}
